/**
 * C Implementation: grib_set_pv
 *
 * Description: how to set pv (vertical coordinate parameters)
 *
 */
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include "eccodes.h"

static void usage(const char *prog)
{
    fprintf(stderr, "usage: %s in out\n", prog);
    exit(1);
}

int sfx_grib_set_pv()
{
    int err = 0;

    const char *infile = "d:/sfxData/ecmwf/eccodes_test_data/regular_latlon_surface.grib1";
    const char *outfile = "d:/temp/out.grib";

    FILE *in = fopen(infile, "rb");
    if (!in)
    {
        fprintf(stderr, "ERROR: unable to open input file %s\n", infile);
        return 1;
    }

    FILE *out = fopen(outfile, "wb");
    if (!out)
    {
        fprintf(stderr, "ERROR: unable to open output file %s\n", outfile);
        fclose(in);
        return 1;
    }

    // create a new handle from a message in a file
    codes_handle *h = codes_handle_new_from_file(0, in, PRODUCT_GRIB, &err);
    if (h == NULL)
    {
        fprintf(stderr, "Error: unable to create handle from file %s\n", infile);
    }

    // ? PVPresent
    CODES_CHECK(codes_set_long(h, "PVPresent", 1), 0);

    double pv[4] = {1, 2, 3, 4};
    size_t pvsize = 4;
    CODES_CHECK(codes_set_double_array(h, "pv", pv, pvsize), 0);

    // Once we set the pv array, the NV key should be also set
    long NV = 0;
    CODES_CHECK(codes_get_long(h, "NV", &NV), 0);
    assert(NV == pvsize);

    // get the coded message in a buffer
    size_t size = 0;
    const void *buffer = NULL;
    CODES_CHECK(codes_get_message(h, &buffer, &size), 0);

    // write the buffer in a file
    if (fwrite(buffer, 1, size, out) != size) {
        perror(infile);
        exit(1);
    }

    codes_handle_delete(h);
    fclose(out);
    fclose(in);
    return 0;
}
